const { Message, UserList, ChatRoom } = require("../models/chat");
module.exports = function setupSockets(io) {
  io.on("connection", async (socket) => {
    const username = socket.handshake.query.username;
    const room = socket.handshake.query.room;
    // 加入房间
    socket.on("joinRoom", async ({ room, username }) => {
      try {
        let chatRoom = await ChatRoom.findOne({ name: room });
        if (!chatRoom) {
          chatRoom = new ChatRoom({
            name: room,
            creator: username,
            members: [],
          });
        }
        chatRoom.members.push(username);
        await chatRoom.save();

        // 加入房间
        socket.join(room);
        io.to(room).emit("roomUsers", chatRoom.members);
        io.to(room).emit("joinMessage", `欢迎${username}进入${room}`);
      } catch (err) {
        console.error(err);
      }
    });

    socket.on("chatMessage", async (msg) => {
      io.to(msg.to).emit("message", msg);

      const newMessage = new Message({
        from: msg.from,
        to: msg.to,
        message: msg.message,
      });
      await newMessage.save();
    });

    // 处理断开连接事件
    socket.on("disconnect", async () => {
      try {
        io.to(room).emit("joinMessage", `${username}退出${room}`);
        // 删除用户信息
        await ChatRoom.updateMany({}, { $pull: { members: username } });
      } catch (err) {}
    });
  });
};
